<template>
  <view class="auth">
    <div class="user-info">
      <open-data class="user-img" type="userAvatarUrl"></open-data>
      <open-data type="userNickName"></open-data>
    </div>
    <button open-type="getUserInfo" type="primary" lang="zh_CN" @getuserinfo="onGotUserInfo">授权登录</button>
  </view>
</template>

<script>
import { getToken } from "@/api";
export default {
  methods: {
//   点击获取用户信息
    onGotUserInfo(e) {
      // console.log(e);
      let { encryptedData, iv, rawData, signature } = e.mp.detail;
      // console.log(encryptedData, iv, rawData, signature);
      wx.login({
        success(res) {
          if (res.code) {
            // 发起网络请求
            // console.log(res.code);
            // 向自己的服务器发送请求，换取 token
            getToken({
              code:res.code,
              encryptedData,
              iv,
              rawData,
              signature
            }).then( res => {
              let { token } = res.message;
              if (token) {
                // console.log('token', token)
                // 获取token 保存到本地
                wx.setStorageSync('token',token);
                wx.showToast({
                  title: '登录成功', //提示的内容,
                  icon: 'success', //图标,
                  duration: 2000, //延迟时间,
                  mask: true, //显示透明蒙层，防止触摸穿透,
                  success: res => {}
                });
                // 跳转返回上一页
                wx.navigateBack({
                  delta: 1
                })
              } else {
                wx.showToast({
                  title: '登录失败', //提示的内容,
                  icon: 'none', //图标,
                  duration: 2000, //延迟时间,
                  mask: true, //显示透明蒙层，防止触摸穿透,
                  success: res => {}
                });
              }
            });
          } else {
              console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.auth {
  margin: 300rpx auto;
  text-align: center;
  font-size: 28rpx;
  .user-info {
    padding: 10rpx 80rpx;
    text-align: center;
    .user-img {
      margin: 0 auto;
      display: block;
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
      border: 7rpx solid #ff2d49;
      overflow: hidden;
    }
  }
  button {
    width: 50%;
    background-color: #ff2d49;
  }
}
</style>